<?php
namespace cosocket\system\base;

use cosocket\system\database\pools\MysqlPool;
use cosocket\system\SqlBuilder;

class Repository
{
    protected $db;
    protected $table;
    protected $primaryKey = 'id';
    protected $builder;

    public function __construct($name = 'default')
    {
        $this->db = MysqlPool::getInstance($name);
        $this->builder = new SqlBuilder();
    }

    public function findById(int $id)
    {
        return $this->findOne([$this->primaryKey => $id]);
    }

    public function findOne(array $conditions)
    {
        $sql = $this->builder->table($this->table)
            ->fields('*');

        foreach ($conditions as $field => $value) {
            $sql->where($field, $value);
        }

        $sql->limit(1);
        return $this->db->query($sql->get())->fetch_assoc();
    }

    public function findAll(array $conditions = [], array $orderBy = [], int $limit = 0, int $offset = 0)
    {
        $sql = $this->builder->table($this->table)
            ->fields('*');

        foreach ($conditions as $field => $value) {
            $sql->where($field, $value);
        }

        foreach ($orderBy as $field => $direction) {
            $sql->orderBy($field, $direction);
        }

        if ($limit > 0) {
            if ($offset > 0) {
                $sql->limit($offset, $limit);
            }else{
                $sql->limit($limit);
            }
        }

        $result = $this->db->query($sql->get());
        return $result->fetch_all(MYSQLI_ASSOC);
    }

    public function getConnection()
    {
        return $this->db;
    }

    public function beginTransaction()
    {
        return $this->db->begin_transaction();
    }

    public function commit()
    {
        return $this->db->commit();
    }

    public function rollback()
    {
        return $this->db->rollback();
    }

}